package com.skaura.cryserver.handler;

import com.alibaba.fastjson.JSONObject;
import com.skaura.cryserver.model.MessageWapper;
import com.skaura.cryserver.model.TestDto;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.Buffer;
import java.nio.ByteBuffer;

public class ClientHandler extends ChannelInboundHandlerAdapter{
    Logger logger = LoggerFactory.getLogger(ClientHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        TestDto testDto = new TestDto();
        testDto.setName("client");
        testDto.setMessage("Hello World");
        String content = JSONObject.toJSONString(testDto);
        logger.info("当前发送的数据是：{}",content);
        ctx.writeAndFlush(new MessageWapper((short) 1,content));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof MessageWapper){
            MessageWapper messageWapper = (MessageWapper) msg;
            if (messageWapper.getType() == 1){
                TestDto testDto = JSONObject.parseObject(messageWapper.getBody(), TestDto.class);
                logger.info("testDto:{}",testDto.toString());
            }
            logger.info(JSONObject.toJSONString(messageWapper));
        }
    }
}
